import axios from 'axios'
import store from '@/store'
import router from '@/router'
// 封装根路径
const request = axios.create({
  baseURL: 'http://www.liulongbin.top:3008'
})
// 请求拦截器使用request
request.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    // 写在return前边,因为return后边的代码执行不了
    if (config.url.startsWith('/my')) {
      config.headers.Authorization = store.state.user.token
    }
    // console.log(config)
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  }
)
request.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    // 如果token无效过期,在响应拦截器设置状态码===401就清除token和用户基本信息并且跳转页面
    if (error.response.status === 401) {
      store.commit('user/updateToken', '')
      store.commit('user/upUser', '')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)
// 今后都使用request发axios请求
export default request
